/***********************************************************************
 * BinTrotter : BitTorrent library/client for the Android operating system.
 *  
 * Copyright (C) 2009, Christopher David Stones (chris.stones@gmail.com)
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************/

package org.bintrotter.metafile;

import org.bintrotter.ClientInfo;
import org.bintrotter.bdecode.*;

import java.util.LinkedList;
import java.util.List;

public class Metafile {
	
	public InfoHash infoHash;
	
	public class Info {
		
		public int piece_length;
		public byte[] pieces;
		public int _private;
		
		public Info(Node<BCodeTree.NodeData> node) {
			
			Node<BCodeTree.NodeData> tempNode;
			
			piece_length = (int)TreeUtils.lookupInDictionary(node, "piece length").data.getLong();
			pieces = TreeUtils.lookupInDictionary(node, "pieces").data.getString();
			
			_private = 0;
			if((tempNode = TreeUtils.lookupInDictionary(node, "private")) != null)
				_private = (int)tempNode.data.getLong();	
		}
	}
	
	public class SingleFileInfo extends Info {
		
		public String 	name;
		public long		length;
		public String	md5sum;
		
		public SingleFileInfo(Node<BCodeTree.NodeData> node) {
			
			super(node);
			
			name = new String(TreeUtils.lookupInDictionary(node, "name").data.getString());
			length = TreeUtils.lookupInDictionary(node,"length").data.getLong();
			
			Node<BCodeTree.NodeData> tempNode;
			md5sum = null;
			if((tempNode = TreeUtils.lookupInDictionary(node, "md5sum")) != null)
				md5sum = new String( tempNode.data.getString());
		}
	}
	
	
	public class MultiFileInfo extends Info {
		
		public class Files
		{
			public long length;
			public String md5sum;
			public List<String> path;
			
			public Files(Node<BCodeTree.NodeData> node)
			{
				length = TreeUtils.lookupInDictionary(node, "length").data.getLong();
				
				Node<BCodeTree.NodeData> tempNode;
				md5sum = null;
				if((tempNode = TreeUtils.lookupInDictionary(node, "md5sum")) != null)
					md5sum = new String( tempNode.data.getString());
				
				Node<BCodeTree.NodeData> pathNode = TreeUtils.lookupInDictionary(node, "path").child;
				
				path = new LinkedList<String>();
				
				while(pathNode != null) {
	
					String str = new String (pathNode.data.getString()); 
					path.add( str );
					pathNode = pathNode.sibling;
					
				}
			}
		}
		
		public String name;
		public List<Files>  files;
		
		public MultiFileInfo(Node<BCodeTree.NodeData> node) {
			
			super(node);
			
			name = new String( TreeUtils.lookupInDictionary(node, "name").data.getString());
			
			Node<BCodeTree.NodeData> fileListNode = TreeUtils.lookupInDictionary(node, "files").child;
			
			files = new LinkedList<Files>();
			
			while(fileListNode != null) {
				
				files.add( new Files( fileListNode ));
				
				fileListNode = fileListNode.sibling;
			}
		}
	}
	
	public MultiFileInfo multiFileInfo;
	public SingleFileInfo singleFileInfo;
	public String announce;
	public List< List<String> > announce_list;
	public int creation_date;
	public String comment;
	public String created_by;
	public String encoding;
	
	
	public Metafile(String fileName) throws Throwable {
			
		infoHash = null;
		announce = null;
		announce_list = null;
		creation_date = 0;
		comment = null;
		created_by = null;
		singleFileInfo = null;
		multiFileInfo = null;
		
		BCodeTree tree = new BCodeTree(fileName);
		
		Node<BCodeTree.NodeData> root = tree.rootNode.child;
		
		parseInfo(root);
		parseAnnounce(root);
		parseAnnounceList(root);
		parseCreationDate(root);
		parseComment(root);
		parseCreatedBy(root);
		parseEncoding(root);
		
		infoHash = new InfoHash(fileName);
	}
		
	private void parseInfo(Node<BCodeTree.NodeData> root) {
		
		/*** dictionary ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"info");
		
		/*** single file or multi-file torrent ? ***/
		if(TreeUtils.lookupInDictionary(node,"files") != null)
			multiFileInfo = new MultiFileInfo(node);
		else 
			singleFileInfo = new SingleFileInfo(node);
	}
	private void parseAnnounce(Node<BCodeTree.NodeData> root) {
		
		/*** string ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"announce");
		
		announce = new String(node.data.getString());
	}
	private void parseAnnounceList(Node<BCodeTree.NodeData> root) {
		
		/*** optional list of lists of strings ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"announce-list");
		
		if(node != null) {
			
			Node<BCodeTree.NodeData> tier1 = node.child;
			
			announce_list = new LinkedList< List<String> >();
			
			while(tier1 != null) {
			
				announce_list.add( new LinkedList<String>() );
				
				Node<BCodeTree.NodeData> tier2 = tier1.child;
				
				while(tier2 != null) {
					
					String str = new String(tier2.data.getString());
					announce_list.get( announce_list.size() -1 ).add(str);			
					tier2 = tier2.sibling;

				}
				tier1 = tier1.sibling;
			}
		}
	}
	private void parseCreationDate(Node<BCodeTree.NodeData> root) {
		
		/*** optional integer ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"creation date");
		
		if(node != null)
			creation_date = (int)node.data.getLong();
	}
	private void parseComment(Node<BCodeTree.NodeData> root) {
		
		/*** optional string ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"comment");
		
		if(node != null)
			comment = new String( node.data.getString() );
	}
	private void parseCreatedBy(Node<BCodeTree.NodeData> root) {
		
		/*** optional string ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"created by");
		
		if(node != null)
			created_by = new String(node.data.getString());
			
	}
	private void parseEncoding(Node<BCodeTree.NodeData> root) {
		
		/*** optional string ***/
		Node<BCodeTree.NodeData> node = TreeUtils.lookupInDictionary(root,"encoding");
		
		if(node != null)
			encoding = new String(node.data.getString());
	}
	public int pieceLength() {
		
		if(singleFileInfo != null)
			return singleFileInfo.piece_length;
		
		return multiFileInfo.piece_length;
	}
	
	public byte[] pieceHash(int piece) {
		
		byte[] pieces = null;
		
		if(singleFileInfo != null)
			pieces = singleFileInfo.pieces; 
		else
			pieces = multiFileInfo.pieces;
		
		byte[] p = new byte[20];
		System.arraycopy(pieces, piece * 20, p, 0, 20);
		
		return p;
	}

	public long length() {
		
		if(singleFileInfo != null)
			return singleFileInfo.length; 
		
		long len = 0;
		
		for( Metafile.MultiFileInfo.Files f : multiFileInfo.files)
			len += f.length;
		
		return len;
	}

	public int pieces() {
		
		long l = length();
		long pl = pieceLength();
		
		if((pl%l)==0)
			return (int)(l/pl);
		
		return (int)(l/pl)+1;
	}
	
	public int blocksPerPiece() {
		
		int srl = ClientInfo.instance().staticRequestLength();
		int pl = pieceLength();
		
		if((pl%srl)==0)
			return pl/srl;
		
		return (pl/srl)+1;
		
	}
}

